package com.stx.jeepay.merchant.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.stx.jeepay.core.aop.MethodLog;
import com.stx.jeepay.core.entity.MchDivisionReceiverEntity;
import com.stx.jeepay.core.entity.MchDivisionReceiverGroupEntity;
import com.stx.jeepay.core.enums.ApiCodeEnum;
import com.stx.jeepay.core.enums.CS;
import com.stx.jeepay.core.expection.BizException;
import com.stx.jeepay.core.model.ApiPageRes;
import com.stx.jeepay.core.model.ApiRes;
import com.stx.jeepay.core.service.MchDivisionReceiverGroupService;
import com.stx.jeepay.core.service.MchDivisionReceiverService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@Api(tags = "分账管理（账号组）")
@RestController
@RequestMapping("api/divisionReceiverGroups")
public class MchDivisionReceiverGroupController extends CommonCtrl {

    @Autowired
    private MchDivisionReceiverGroupService mchDivisionReceiverGroupService;

    @Autowired
    private MchDivisionReceiverService mchDivisionReceiverService;

    @ApiOperation("账号组列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "pageNumber", value = "分页页码", dataType = "int", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "分页条数（-1时查全部数据）", dataType = "int", defaultValue = "20"),
            @ApiImplicitParam(name = "receiverGroupId", value = "账号组ID", dataType = "Long"),
            @ApiImplicitParam(name = "receiverGroupName", value = "组名称")
    })
    @PreAuthorize("hasAnyAuthority( 'ENT_DIVISION_RECEIVER_GROUP_LIST' )")
    @GetMapping
    public ApiPageRes<MchDivisionReceiverGroupEntity> list() {
        MchDivisionReceiverGroupEntity queryObject = getObject(MchDivisionReceiverGroupEntity.class);

        LambdaQueryWrapper<MchDivisionReceiverGroupEntity> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(MchDivisionReceiverGroupEntity::getMchNo, getCurrentMchNo());

        if (StringUtils.isNotEmpty(queryObject.getReceiverGroupName())) {
            queryWrapper.like(MchDivisionReceiverGroupEntity::getReceiverGroupName, queryObject.getReceiverGroupName());
        }

        if (queryObject.getReceiverGroupId() != null) {
            queryWrapper.eq(MchDivisionReceiverGroupEntity::getReceiverGroupId, queryObject.getReceiverGroupId());
        }

        queryWrapper.orderByDesc(MchDivisionReceiverGroupEntity::getCreatedAt);

        IPage<MchDivisionReceiverGroupEntity> pages = mchDivisionReceiverGroupService.page(getIPage(true), queryWrapper);
        return ApiPageRes.pages(pages);
    }

    @ApiOperation("新增分账账号组")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "autoDivisionFlag", value = "自动分账组（当订单分账模式为自动分账，改组将完成分账逻辑） 0-否 1-是", required = true, dataType = "Byte"),
            @ApiImplicitParam(name = "receiverGroupName", value = "组名称", required = true)
    })
    @PreAuthorize("hasAuthority( 'ENT_DIVISION_RECEIVER_GROUP_ADD' )")
    @MethodLog(remark = "新增分账账号组")
    @PostMapping
    public ApiRes add() {
        MchDivisionReceiverGroupEntity record = getObject(MchDivisionReceiverGroupEntity.class);
        record.setMchNo(getCurrentMchNo());
        record.setCreatedUid(getCurrentUser().getSysUser().getSysUserId());
        record.setCreatedBy(getCurrentUser().getSysUser().getRealname());
        if (mchDivisionReceiverGroupService.save(record)) {
            //更新其他组为非默认分账组
            if (record.getAutoDivisionFlag() == CS.YES) {
                mchDivisionReceiverGroupService.update(new LambdaUpdateWrapper<MchDivisionReceiverGroupEntity>()
                        .set(MchDivisionReceiverGroupEntity::getAutoDivisionFlag, CS.NO)
                        .eq(MchDivisionReceiverGroupEntity::getMchNo, getCurrentMchNo())
                        .ne(MchDivisionReceiverGroupEntity::getReceiverGroupId, record.getReceiverGroupId()));
            }
        }
        return ApiRes.ok();
    }

    @ApiOperation("账号组详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "recordId", value = "账号组ID", required = true, dataType = "Long")
    })
    @PreAuthorize("hasAuthority( 'ENT_DIVISION_RECEIVER_GROUP_VIEW' )")
    @GetMapping("/{recordId}")
    public ApiRes detail(@PathVariable("recordId") Long recordId) {
        MchDivisionReceiverGroupEntity record = mchDivisionReceiverGroupService
                .getOne(new LambdaQueryWrapper<MchDivisionReceiverGroupEntity>()
                        .eq(MchDivisionReceiverGroupEntity::getMchNo, getCurrentMchNo())
                        .eq(MchDivisionReceiverGroupEntity::getReceiverGroupId, recordId));

        if (record == null) {
            throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_SELETE);
        }
        return ApiRes.ok(record);
    }

    @ApiOperation("更新分账账号组")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "recordId", value = "账号组ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "autoDivisionFlag", value = "自动分账组（当订单分账模式为自动分账，改组将完成分账逻辑） 0-否 1-是", required = true, dataType = "Byte"),
            @ApiImplicitParam(name = "receiverGroupName", value = "组名称", required = true)
    })
    @PreAuthorize("hasAuthority( 'ENT_DIVISION_RECEIVER_GROUP_EDIT' )")
    @MethodLog(remark = "更新分账账号组")
    @PutMapping("/{recordId}")
    public ApiRes update(@PathVariable("recordId") Long recordId) {
        MchDivisionReceiverGroupEntity reqRecord = getObject(MchDivisionReceiverGroupEntity.class);

        MchDivisionReceiverGroupEntity record = new MchDivisionReceiverGroupEntity();
        record.setReceiverGroupName(reqRecord.getReceiverGroupName());
        record.setAutoDivisionFlag(reqRecord.getAutoDivisionFlag());

        LambdaUpdateWrapper<MchDivisionReceiverGroupEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(MchDivisionReceiverGroupEntity::getReceiverGroupId, recordId);
        updateWrapper.eq(MchDivisionReceiverGroupEntity::getMchNo, getCurrentMchNo());

        if (mchDivisionReceiverGroupService.update(record, updateWrapper)) {
            //更新其他组为非默认分账组
            if (record.getAutoDivisionFlag() == CS.YES) {
                mchDivisionReceiverGroupService.update(new LambdaUpdateWrapper<MchDivisionReceiverGroupEntity>()
                        .set(MchDivisionReceiverGroupEntity::getAutoDivisionFlag, CS.NO)
                        .eq(MchDivisionReceiverGroupEntity::getMchNo, getCurrentMchNo())
                        .ne(MchDivisionReceiverGroupEntity::getReceiverGroupId, recordId));
            }
        }
        return ApiRes.ok();
    }

    @ApiOperation("删除分账账号组")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "recordId", value = "账号组ID", required = true, dataType = "Long")
    })
    @PreAuthorize("hasAuthority('ENT_DIVISION_RECEIVER_GROUP_DELETE')")
    @MethodLog(remark = "删除分账账号组")
    @DeleteMapping("/{recordId}")
    public ApiRes del(@PathVariable("recordId") Long recordId) {
        MchDivisionReceiverGroupEntity entity = mchDivisionReceiverGroupService.getOne(new LambdaQueryWrapper<MchDivisionReceiverGroupEntity>()
                .eq(MchDivisionReceiverGroupEntity::getReceiverGroupId, recordId)
                .eq(MchDivisionReceiverGroupEntity::getMchNo, getCurrentMchNo()));
        if (entity == null) {
            throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_SELETE);
        }

        if (mchDivisionReceiverService.count(new LambdaQueryWrapper<MchDivisionReceiverEntity>().eq(MchDivisionReceiverEntity::getReceiverGroupId, recordId)) > 0) {
            throw new BizException("该组存在账号，无法删除");
        }

        mchDivisionReceiverGroupService.removeById(recordId);
        return ApiRes.ok();
    }
}
